package com.htfg.cardActivate.user.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.htfg.cardActivate.config.OSSUploadUtil;
import com.htfg.cardActivate.core.ResultCode;
import com.htfg.cardActivate.core.ResultData;
import com.htfg.cardActivate.user.dao.BankPersonMapper;
import com.htfg.cardActivate.user.dao.UserMapper;
import com.htfg.cardActivate.user.entity.BankPerson;
import com.htfg.cardActivate.user.entity.User;
import com.htfg.cardActivate.user.service.UserService;
import com.htfg.cardActivate.util.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: 王晨缘
 * @Date: 2018/10/24 0024 17:06
 * @Description: 银行人员和客户的管理
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
    private final Logger logger = Logger.getLogger(UserServiceImpl.class);
    @Autowired
    private BankPersonMapper bankPersonMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private UserMapper userMapper;
    /**
     * 注册银行人员
     *
     * @param username
     * @param mobile
     * @return
     */
    @Override
    public ResultData registerBankPerson(String username, String mobile) {
        BankPerson bankPerson = bankPersonMapper.selectByPhone(mobile);
        if (bankPerson == null) {
            bankPerson = new BankPerson();
            bankPerson.setUid(UUIDUtil.getUUID());
            bankPerson.setUsername(username);
            bankPerson.setMobile(mobile);
            bankPerson.setCreateTime(DateUtil.getNewDateYmdHms());
            bankPerson.setUpdateTime(DateUtil.getNewDateYmdHms());
            int i = bankPersonMapper.insertSelective(bankPerson);
            if (i >= 1) {
                logger.info("注册用户成功:" + username + ";手机号:" + mobile + ";用户唯一标识:" + bankPerson.getUid());
                return ResultData.successDate(bankPerson);
            } else {
                logger.info("注册用户失败:" + username + ";手机号:" + mobile);
                return ResultData.failDate(ResultCode.REGISTER_FAIL.getCode(), ResultCode.REGISTER_FAIL.getMsg(), "");
            }
        }else{
            logger.info("用户已经注册:" + username + ";手机号:" + mobile);
            return ResultData.failDate(ResultCode.REGISTER_FAIL_PHONE.getCode(), ResultCode.REGISTER_FAIL_PHONE.getMsg(), "");
        }

    }

    /**
     * 发送手机验证码
     * @param mobile
     * @return
     */
    @Override
    public ResultData sendMobile(String mobile) throws ClientException {
        String random = RandomUtils.getRandom(4);
        redisTemplate.opsForValue().set("cardActivate"+mobile,random,300, TimeUnit.SECONDS);
        SendSmsResponse sendSmsResponse = SmsUtil.sendSms(mobile, random);
        logger.info("发送手机验证码:"+random+";手机号:"+mobile+";发送结果:"+sendSmsResponse);
        if("OK".equals(sendSmsResponse.getCode())) {
            return ResultData.successDate(sendSmsResponse);
        }else{
            return ResultData.failDate(ResultCode.SENDMSG_FAIL.getCode(),ResultCode.REGISTER_FAIL.getMsg(),sendSmsResponse);
        }
    }

    /**
     * 添加客户信息
     * @param user
     * @return
     */
    @Override
    public ResultData registerUser(User user) {
        logger.info("注册客户信息:"+user);
        User user1 = userMapper.selectByPrimaryKey(user.getUid());
        if(user1 == null) {
            int i = userMapper.insertSelective(user);
            if (i >= 1) {
                return ResultData.successDate(user);
            }
        }
        return ResultData.failDate(ResultCode.REGISTER_FAIL_PHONE.getCode(),ResultCode.REGISTER_FAIL_PHONE.getMsg(),user1);
    }

    /**
     * 查看附近业务人员
     * @param uid
     * @param bankName
     * @param lon
     * @param lat
     * @return
     */
    @Override
    public ResultData nearbyBusinessPeople(String uid, String bankName, Double lon, Double lat,Integer pageIndex,Integer pageSize) {
        logger.info("uid : "+uid+";bankName : "+bankName+";lon : "+lon+";lat : "+lat);
        Map<String,Object> map=new HashMap<>();
        if(lon==null || lat ==null){
            User user = userMapper.selectByPrimaryKey(uid);
            if(user==null){
                return ResultData.failDate(ResultCode.USER_NOT_EXIST.getCode(),ResultCode.USER_NOT_EXIST.getMsg(),"");
            }else{
                List<Map<String, Object>> maps = bankPersonMapper.selectDistance(user.getLon(), user.getLat(),bankName,(pageIndex - 1) * pageSize, pageSize);
                int i = bankPersonMapper.selectDistanceCount(bankName);
                map.put("list",maps);
                map.put("listCount",i);
                return ResultData.successDate(map);
            }
        }else{
            List<Map<String, Object>> maps = bankPersonMapper.selectDistance(lon,lat,bankName,(pageIndex - 1) * pageSize, pageSize);
            int i = bankPersonMapper.selectDistanceCount(bankName);
            map.put("list",maps);
            map.put("listCount",i);
            return ResultData.successDate(map);
        }
    }

    @Override
    public ResultData registerBankPersonDetail(String uid, String bankName, String province,
                                               String city, String workNumber, MultipartFile file,
                                               double lon, double lat) {
        String fileUrl = OSSUploadUtil.uploadFile(file);
        logger.info("上传至阿里云获得图片链接:"+fileUrl);
        BankPerson bankPerson = bankPersonMapper.selectByPrimaryKey(uid);
        logger.info("uid : "+uid+";银行人员信息 : "+bankPerson);
        int i;
        if(bankPerson!=null){
            bankPerson.setBank(bankName);
            bankPerson.setCity(city);
            bankPerson.setProvince(province);
            bankPerson.setWorkImg(fileUrl);
            bankPerson.setWorkNumber(workNumber);
            bankPerson.setUpdateTime(DateUtil.getNewDateYmdHms());
            bankPerson.setLon(lon);
            bankPerson.setLat(lat);
             i = bankPersonMapper.updateByPrimaryKeySelective(bankPerson);
        }else{
            return ResultData.failDate(ResultCode.USER_NOT_EXIST.getCode(),ResultCode.USER_NOT_EXIST.getMsg(),uid);
        }
        if(i>=1){
            return ResultData.successDate(bankPerson);
        }else{
            return ResultData.failDate(ResultCode.USER_NOT_EXIST.getCode(),ResultCode.USER_NOT_EXIST.getMsg(),uid);
        }
    }
}
